package article

import (
	"yunj/app/service/admin/articleservice"
	"yunj/pkg/yunj/app/controller/admin"
	"yunj/pkg/yunj/core/enum/errcode"
	"yunj/pkg/yunj/core/response"
	"yunj/pkg/yunj/util"

	"github.com/gin-gonic/gin"
)

type Article struct {
	admin.Controller
}

// 列表
func (ctrl *Article) List(ctx *gin.Context) {
	ctrl.RenderTable(ctx, articleservice.ArticlePage.ListBuilder(ctx))
}

// 添加
func (ctrl *Article) Add(ctx *gin.Context) {
	if util.IsAsync(ctx) {
		id, err := articleservice.ArticlePage.HandleAdd(ctx)
		if err != nil {
			response.Fail(ctx, err.Error())
		} else {
			response.Success(ctx, map[string]any{
				"redirect": util.BuildAdminUrl("/article/list/edit", map[string]any{"id": id}),
			})
		}
		return
	}
	fields, err := articleservice.ArticlePage.FormFields(ctx, false)
	if err != nil {
		util.RedirectAdminTips(ctx, errcode.ERROR, err.Error())
		return
	}
	ctrl.Render(ctx, "article/form", map[string]any{
		"formId": articleservice.FORM_ID,
		"fields": fields,
	})
}

// 编辑
func (ctrl *Article) Edit(ctx *gin.Context) {
	if util.IsAsync(ctx) {
		err := articleservice.ArticlePage.HandleEdit(ctx)
		if err != nil {
			response.Fail(ctx, err.Error())
		} else {
			response.Success(ctx, "编辑成功")
		}
		return
	}
	fields, err := articleservice.ArticlePage.FormFields(ctx, true)
	if err != nil {
		util.RedirectAdminTips(ctx, errcode.ERROR, err.Error())
		return
	}
	ctrl.Render(ctx, "article/form", map[string]any{
		"formId": articleservice.FORM_ID,
		"fields": fields,
	})
}
